package com.twh.www.service.login.impl;

import com.twh.www.entity.WnAdmin;
import com.twh.www.entity.WnUser;
import com.twh.www.mapper.WnAdminMapper;
import com.twh.www.mapper.WnUserMapper;
import com.twh.www.service.login.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

/**
 * 用户名密码登录适配器
 */
@Component
public class PasswordLoginAdapter implements LoginStrategy {
    @Autowired
    private WnUserMapper userMapper;
    @Autowired
    private WnAdminMapper adminMapper;

    @Override
    public WnUser login(Object... credentials) {
        if (credentials.length < 2) {
            return null;
        }
        String account = (String) credentials[0];
        String password = (String) credentials[1];
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // 1. 尝试从 wn_admin 表查找管理员
        WnAdmin admin = adminMapper.getAdminByAccount(account);
        if (admin != null && encryptedPassword.equals(admin.getPassword())) {
            WnUser adminUser = new WnUser();
            adminUser.setId(admin.getId());
            adminUser.setAccount(admin.getAccount());
            adminUser.setStatus(admin.getStatus());
            adminUser.setRole("admin");
            if ("2".equals(admin.getStatus())) {
                adminUser.setErrorMessage("您的账号已被冻结，请联系管理员。");
                return adminUser;
            } else if ("3".equals(admin.getStatus())) {
                adminUser.setErrorMessage("您的账号已被拉入黑名单，无法登录。");
                return adminUser;
            } else if ("4".equals(admin.getStatus())) {
                adminUser.setErrorMessage("您的账号已被删除，无法登录。");
                return adminUser;
            }
            return adminUser;
        }

        // 2. 如果不是管理员，尝试从 wn_user 表查找普通用户
        WnUser user = userMapper.getUserByAccount(account);
        if (user != null && encryptedPassword.equals(user.getPassword())) {
            if ("2".equals(user.getStatus())) {
                user.setErrorMessage("您的账号已被冻结，请联系管理员。");
                return user;
            } else if ("3".equals(user.getStatus())) {
                user.setErrorMessage("您的账号已被拉入黑名单，无法登录。");
                return user;
            } else if ("4".equals(user.getStatus())) {
                user.setErrorMessage("您的账号已被删除，无法登录。");
                return user;
            }
            return user;
        }

        return null;
    }

    @Override
    public String getLoginType() {
        return "PASSWORD";
    }
} 